package com.iakuil.poc.service;

import com.iakuil.poc.dao.UserRepository;
import com.iakuil.poc.domain.User;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.data.domain.Example;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Querying the details of user for Security Sever From DB
 */
@Service
public class JdbcUserDetailsService implements UserDetailsService {

    @Resource
    @PersistenceContext
    private EntityManager entityManager;

    private JPAQueryFactory queryFactory;

    private final UserRepository userRepository;

    public JdbcUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @PostConstruct
    public void init() {
        queryFactory = new JPAQueryFactory(entityManager);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User condition = new User();
        condition.setUsername(username);
        return userRepository.findOne(Example.of(condition))
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
    }

//    private Collection<? extends GrantedAuthority> getGrantedAuthorities(User user) {
//        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
//        for (Role role : user.getRoles()) {
//            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
//        }
//        return authorities;
//    }
}
